package com.ruben.adapter.common;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.imagepreview.R;
import com.hujiang.restvolley.download.RestVolleyDownload;
import com.ruben.utils.ToastUtils;
import com.squareup.okhttp.Headers;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import uk.co.senab.photoview.PhotoView;

public class PictureAdapter extends PagerAdapter {

    private static final String TAG = "PictureAdapter";
    private List<WeakReference<PhotoView>> cacheViews;
    private List<String> imageUrls;
    private Context context;
    private ItemTapClickListener itemTapClickListener;

    public PictureAdapter(List<String> data, Context context, ItemTapClickListener itemTapClickListener) {
        imageUrls = data;
        cacheViews = new ArrayList<>();
        this.context = context;
        this.itemTapClickListener = itemTapClickListener;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        PhotoView httpImageView;
        // 如果缓存为空
        if (cacheViews.isEmpty()) {
            // 默认初始化
            initView(4);
        }
        httpImageView = cacheViews.get(0).get();

        // 由于用了弱引用，所以当垃圾回收器进行回收的时候就回收所有内存
        if (httpImageView == null) {
            // 需要先清理，GC后对象内存被回收
            cacheViews.clear();
            initView(2);
            httpImageView = cacheViews.get(0).get();
            Log.d(TAG, "----发生了GC----  init view size : " + cacheViews.size());
        }

        ViewGroup parent = (ViewGroup) httpImageView.getParent();
        // 这里的parent是ViewPager
        if (parent != null) {
            Log.d(TAG, "parent : " + parent.toString());
        } else {
            container.addView(httpImageView);
        }
        // 获取url
        String url = imageUrls.get(position);
        // 加载网络图片
        Glide.with(context).load(url)
                // 加载失败时显示
                .error(R.mipmap.error)
                // 加载中
                .placeholder(R.mipmap.loading)
                // 添加监听
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        // 输出日志
                        Log.d(TAG, "onException: " + e.toString() + "  model:" + model + " isFirstResource: " + isFirstResource);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        // 输出日志
                        Log.e(TAG, "model:" + model + " isFirstResource: " + isFirstResource);
                        return false;
                    }
                })
                // 开启缓存
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                // 把加载的图片放入PhotoView
                .into(httpImageView);

        // 移除第一个元素
        cacheViews.remove(0);
        // 设置监听
        httpImageView.setOnViewTapListener((view, x, y) -> itemTapClickListener.onClick());
        // 设置长按监听
        httpImageView.setOnLongClickListener(v -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            AlertDialog alertDialog = builder.setPositiveButton("保存", null)
                    .setNegativeButton("收藏", (dialog, which) -> {
                        ToastUtils.shortToast("我还没做收藏功能!");
                    }).create();
            alertDialog.show();
            alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v1 -> {
                String filename = url.substring(url.lastIndexOf("/"));
                String localPath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + filename;
                RestVolleyDownload.download(context, url, localPath, new RestVolleyDownload.OnDownloadListener() {
                    @Override
                    public void onDownloadStart(String url) {

                    }

                    @Override
                    public void onDownloadSuccess(String url, File file, int httpCode, Headers headers) {
                        ToastUtils.shortToast("保存成功,文件地址：" + localPath);
                    }

                    @Override
                    public void onDownloadFailure(String url, Exception e, int httpCode, Headers headers) {
                        ToastUtils.shortToast("保存失败");
                    }

                    @Override
                    public void onDownloadProgress(String url, int downloadBytes, int contentLength, File file, int httpCode, Headers headers) {

                    }
                });
            });
            return true;
        });
        return httpImageView;
    }

    /**
     * 初始化视图
     *
     * @param num
     */
    public void initView(int num) {
        for (int i = 0; i < num; i++) {
            // 创建图片
            PhotoView image = new PhotoView(context);
            // 开启缩放
            image.setZoomable(true);
            // 设置最大放大倍数
            image.setMaximumScale(4.0f);
            // 设置最小缩小倍数
            image.setMinimumScale(1.0f);
            // 设置布局
            image.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            // 开启边框适应
            image.setAdjustViewBounds(true);
            // 把图片按比例调整到View的宽度并居中显示
            image.setScaleType(ImageView.ScaleType.FIT_CENTER);
            // 添加缓存
            cacheViews.add(new WeakReference<>(image));
        }
    }

    /**
     * 获取图片数
     *
     * @return
     */
    @Override
    public int getCount() {
        return imageUrls.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    /**
     * 销毁组件并添加进缓存
     *
     * @param container
     * @param position
     * @param object
     */
    @Override
    public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
        cacheViews.add(new WeakReference<>((PhotoView) object));
        container.removeView((View) object);
    }

    public interface ItemTapClickListener {
        void onClick();
    }

}